/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-07-24
*/
package com.rzico.order.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Member;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.basics.service.MemberService;
import com.rzico.core.service.SysSequenceService;
import com.rzico.entity.Filter;
import com.rzico.entity.Pageable;
import com.rzico.entity.PageResult;
import com.rzico.order.entity.Askfor;
import com.rzico.order.entity.Order;
import com.rzico.order.entity.OrderItem;
import com.rzico.order.entity.VirtualStock;
import com.rzico.order.enumx.OrderShippingStatusEnum;
import com.rzico.order.model.VirtualStockVo;
import com.rzico.order.service.AskforService;
import com.rzico.order.service.OrderItemService;
import com.rzico.order.service.OrderService;
import com.rzico.order.service.VirtualStockService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.Api;
import com.rzico.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Date;

/**
 * 虚拟商品库存控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-07-24
 */
@Api(description = "虚拟商品库存接口")
@RestController
@RequestMapping("/admin/virtualStock")
public class VirtualStockAdminController extends BaseController {

    @Autowired
    private VirtualStockService virtualStockService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private AskforService askforService;

    @Autowired
    private SysSequenceService sysSequenceService;

    /**
     * 分页查询虚拟商品库存
     *
     * @return
     */
    @ApiOperation("分页查询虚拟商品库存")
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId", value = "会员ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "productId", value = "商品ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "subType", value = "类型 {0.产品,1:套餐,2:水票,3.压桶}", dataType = "Long", paramType = "query")
    })
    public CommResult<VirtualStock> list(Long memberId,Long productId,Integer subType, Pageable pageable) {

        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);

        Member member = memberService.findById(memberId);

        if (member!=null){
            params.put("memberId", member.getId());
        }
        if (productId!=null){
            params.put("productId", productId);
        }
        if (subType!=null){
            params.put("subType", subType);
        }

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<VirtualStockVo> list = virtualStockService.selectVoList(params);
        PageResult<VirtualStockVo> pageResult = new PageResult<VirtualStockVo>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);

    }



    /**
     * 退桶
     *
     * @param id
     * @return
     */
    @ApiOperation("退桶")
    @PostMapping("/refund")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "电子券ID", dataType = "String", paramType = "query")
    })
    public CommResult<Askfor> refund(Long id) {

        VirtualStock virtualStock = virtualStockService.findById(id);

        if (virtualStock==null) {
            return CommResult.error("无效ID");
        }

        Order order = orderService.selectByPrimaryKey(virtualStock.getOrderId());

        if (order.getGiftCardId()!=null) {
            return CommResult.error("礼卡订单不能退");
        }
        if (order.getGroupBuyId()!=null) {
            return CommResult.error("团购订单不能退");
        }

        //检查退货状态
        Map<String,Object> params = new HashMap<>();
        params.put("orderId",id);
        params.put("askfored",true);

        Integer w = askforService.selectRowCount(params);
        if (w>0) {
            return CommResult.error("不能重复退款");
        }

        Askfor askfor = null;
        try {

            List<OrderItem> itemList = new ArrayList<>();
            order.setItemList(orderItemService.getItemList(order.getId()));
            for (OrderItem orderItem:order.getItemList()) {
                if (orderItem.getProductId().equals(virtualStock.getProductId())) {
                    orderItem.setReturnQuantity(orderItem.getAvailableReturnQuantity());
                    itemList.add(orderItem);
                }
            }

            askfor = askforService.askfor(virtualStock.getOrderId(), itemList, sysSequenceService.generate("askfor"), "", "商户发起退货");
        } catch (Exception e) {
            return CommResult.error(e.getMessage());
        }

        //检查是否符合极速退款条件,商家发起退款，默认自动
        try {

            askforService.confirm(askfor.getId());
            //不能自动打款，只能自动同意
//            List<Refunds> refundsList = askforService.refund(askfor.getId(), sysSequenceService.generate("refunds"));
//            for (Refunds refunds:refundsList) {
//                //TODO发送退款通知
//                Attach attachQueue = new Attach();
//                attachQueue.setCode("0000");
//                attachQueue.setId(String.valueOf(refunds.getId()));
//                attachQueue.setQueue("queue.refunds.submit");
//                Message message = MessageBuilder
//                        .withBody(JSON.toJSONString(attachQueue).getBytes())
//                        .setContentType(MessageProperties.CONTENT_TYPE_JSON)
//                        .build();
//                CorrelationData correlationData = new CorrelationData();
//                correlationData.setId(UUID.randomUUID().toString());
//                logger.info("发送 MQ");
//                rabbitTemplate.convertAndSend("directExchange",attachQueue.getQueue()+".key", message, correlationData);
//
//            }

        } catch (Exception e) {
            logger.error(e.getMessage());
            return CommResult.error(e.getMessage());
        }

//        askfor = askforService.findById(askfor.getId());
//        return CommResult.success(askfor);
//
//        if (shopId==null) {
//            return CommResult.error("退货仓库不能为空");
//        }
//        if (orderDate==null) {
//            return CommResult.error("退货日期不能为空");
//        }
//        orderService.returns(id, shopId ,orderDate,itemList,sysSequenceService.generate("warehouse"));

        Order result = orderService.findById(id);
        return CommResult.success(result);

    }


}
